"""添加新组件路由"""

from case_convert import pascal_case, kebab_case


def read_lines(path):
    """读取文件"""
    with open(path, encoding="utf8") as file:
        return file.read().split("\n")


def write_lines(path, lines):
    """写文件"""
    with open(path, mode="w", encoding="utf8") as file:
        file.write("\n".join(lines))


def add_route(route_name):
    """添加路由"""
    path = r"src\app\app.routes.ts"
    lines = read_lines(path)
    add_import(lines, route_name)
    add_route_def(lines, route_name)
    modify_home(lines, route_name)
    write_lines(path, lines)


def add_import(lines: list, route_name):
    """添加导入
    import { PaginationDisableDemoComponent } from './pagination/pagination-disable-demo.component';
    """
    # 不重复导入
    import_definition = get_import(route_name)
    for item in lines:
        if item.startswith(import_definition):
            return

    # 找到最后一个导入语句的位置
    position = find_last_import(lines)
    lines.insert(position + 1, import_definition)


def find_last_import(lines):
    """找到最后一个导入语句"""
    last_import = -1
    for i, item in enumerate(lines):
        if item.startswith("import {"):
            last_import = i
    return last_import


def get_import(route_name):
    """取得导入语句

    >>> get_import('pagination/disable-demo')
    "import { PaginationDisableDemoComponent } from './pagination/pagination-disable-demo.component';"
    """
    return f"import {{ {get_component_name(route_name)} }} from '{get_component_path(route_name)}';"


def get_component_name(route_name):
    """取得组件名

    >>> get_component_name('pagination/disable-demo')
    PaginationDisableDemoComponent
    """
    name = route_name.replace("/", "-") + "-component"
    return pascal_case(name)


def get_component_path(route_name):
    """取得组件路径

    >>> get_component_path('pagination/disable-demo')
    './pagination/pagination-disable-demo.component'
    """
    category, name = route_name.split("/")
    return f"./{category}/{category}-{kebab_case(name)}.component"


def add_route_def(lines, route_name):
    """添加路由定义"""
    position = fine_last_route(lines)
    route = (
        f"  {{ path: '{route_name}', component: {get_component_name(route_name)} }},"
    )
    lines.insert(position, route)


def fine_last_route(lines):
    """找到最后一个路由"""
    for i, line in enumerate(lines):
        if line.strip().startswith("// last"):
            return i


def modify_home(lines, route_name):
    """修改首页"""
    position = find_home_redirect(lines)
    lines[position] = f"      redirectTo: '/{route_name}',"


def find_home_redirect(lines):
    """找到首页跳转"""
    for i, line in enumerate(lines):
        if line.strip().startswith("redirectTo"):
            return i
